package org.ands.apps;

import java.io.File;

import java.io.PrintStream;
import java.util.List;
import java.util.Map;

import org.ands.data.Contents;
import org.ands.xml.DOMHelper;
import org.ands.xml.DOMHelperConstruct;
import org.ands.xml.XmlWriter;
import org.w3c.dom.Document;
import javax.xml.namespace.NamespaceContext;

public class DOMDocumentConstructor {
	
	/**
	 * Constructs a Document from a list of XMLContents objects.
	 *
	 * @param namespaceURI - ok if null
	 * @param xmlContentsAllRegistryObjectsMap the xml contents all registry objects map
	 * 
	 * @return 
	 * @return          				<code>Document</code> if the Document was
	 * created and populated successfully;
	 * @throws Exception the exception
	 * @see       	Contents
	 * @since     	1.0
	 */
	public DOMHelper documentFromXMLContents(
			final NamespaceContext namespaceContext, 
			final String namespaceURI,
			final String qualifiedName,
			final Map<String, String> docRootAttributeMap,
			final Map<Integer, List<Contents>> xmlContentsAllRegistryObjectsMap) 
					throws Exception{
		
		if((xmlContentsAllRegistryObjectsMap == null) || (xmlContentsAllRegistryObjectsMap.size() <= 0)){
			throw new Exception("No XMLContents provided.");
		}
		
		DOMHelperConstruct domHelper = new DOMHelperConstruct(namespaceContext, namespaceURI, qualifiedName, docRootAttributeMap);
		
		for(Map.Entry<Integer, List<Contents>> xmlContentList : xmlContentsAllRegistryObjectsMap.entrySet()){
			List<Contents> xmlContentsList = (List<Contents>) xmlContentList.getValue();
			if((xmlContentsList == null) || (xmlContentsList.isEmpty())){
				throw new Exception("Invalid List of XMLContents");
			}
			
			for(Contents xmlContents : xmlContentsList)
			{
				String xpath = xmlContents.getXpath();
				if((xpath == null) || (xpath.length() <= 0)){
					throw new Exception("No xpath found in list of XMLContents.");
				}
				
				String value = xmlContents.getValue();
				if(value == null){ // Though it's ok if it's an empty string
					throw new Exception("No value found in list of XMLContents.");
				}
				
				domHelper.createXmlAsPerXpath(namespaceURI, xpath, value);
			}
			
		}
		
		return domHelper;
	}
	
	public void writeDocumentToFile(final Document document, final String xmlOutFileName) throws Exception{
		assert(document != null);
		
		if(!document.hasChildNodes()){
			throw new Exception("Document has no children");
		}
		
		File xmlOutFile = new File(xmlOutFileName);
		
		PrintStream printStream = new PrintStream(xmlOutFile);
		XmlWriter writer = new XmlWriter();
		writer.writeToStream(document, printStream);
		
		System.out.println("RIFCS xml has been written to ["+xmlOutFileName+"].");
	}

}
